package cmd

import (
	"fmt"
	"github.com/spf13/cobra"
	"net"
	"time"
)

func init() {
	dialnCmd := &cobra.Command{
		Use:   "dial",
		Short: "连接端口",
		Long:  `连接端口...`,
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Println("连接地址:", args)
			if len(args) > 0 {
				fmt.Println("开始连接:", args[0])
				dial(args[0])
			} else {
				fmt.Println("参数不可以为空!")
			}
		},
	}
	rootCmd.AddCommand(dialnCmd)
}

func dial(address string) {
	//conn, err := net.Dial("tcp", address)
	connTimeout := 3 * time.Second
	conn, err := net.DialTimeout("tcp", address, connTimeout)
	if err != nil {
		fmt.Println("net.Dial 连接错误：", err)
		return
	}
	if conn == nil {
		fmt.Println(">>>>>>>>连接错误:", address)
		return
	}
	fmt.Println(">>>>>>>>连接成功:", address)
	defer conn.Close() // 关闭连接
}
